const sharp = require('sharp');
const fs = require('fs');
const path = require('path');


function batchCompress(params) {
    // 设置输入和输出文件夹
    const inputDir = `./resources/${params.folderName}`;
    const outputDir = `./resources/${params.folderName}_compress`;

    // 获取临时目录下的文件并删除
    function delFile(folderPath) {
        let dirPath = path.resolve(__dirname, folderPath);
        let dirList = fs.readdirSync(dirPath);
        dirList = dirList.filter(x => x !== '.DS_Store');
        if (!dirList.length && folderPath.slice(-4) !== 'temp') {
            fs.rmdirSync(dirPath);
        }
        for (let i = 0; i < dirList.length; i++) {
            let item = dirList[i];
            let curPath = `${folderPath}/${item}`;
            let filePath = path.resolve(__dirname, curPath);
            let stats = fs.statSync(filePath);

            if (stats.isDirectory()) {
                delFile(curPath);
            }

            if (stats.isFile()) {
                fs.unlinkSync(filePath);
            }
        }
    }
    const isExists = fs.existsSync(outputDir);
    if (isExists) {
        delFile(outputDir);
        fs.rmdirSync(outputDir);
    }


    // 创建压缩目录
    fs.mkdirSync(outputDir);

    // 读取输入文件夹中的所有文件
    fs.readdir(inputDir, (err, files) => {
        if (err) {
            console.error('Error reading input directory:', err);
            return;
        }

        // 遍历每个文件并压缩
        files.forEach(file => {
            const inputPath = path.join(inputDir, file);
            const outputPath = path.join(outputDir, file);

            // 使用 sharp 库来压缩图片
            sharp(inputPath)
                .jpeg({ quality: params.quality || 100 })
                .resize({ width: params.width || 600 }) // 设置新的宽度为800像素
                .toFile(outputPath, (err, info) => {
                    if (err) {
                        console.error('Error compressing image:', err);
                    } else {
                        console.log('Image compressed:', info);
                    }
                });
        });
    });
}

const params = {
    folderName: '小程序切图', // 文件夹名称
    width: 600, // 图片宽度
    quality: 95 // 图片质量
}
batchCompress(params);
